import re
import os
import os.path
import subprocess
import shlex

from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager


import requests
import json
import sys
import os

headers = {'Content-Type': 'application/json;charset=utf-8'}
api_send_url = "http://10.147.113.190:10001/cgi-bin/webhook/send?key=f4bf964d-97cb-44a9-88d3-eb5593643c21"
api_upload_url = "http://10.147.113.190:10001/cgi-bin/webhook/upload_media?key=f4bf964d-97cb-44a9-88d3-eb5593643c21&type=file" # 上传文件接口

def wx_upload(file):
    data = {'file': open(file, 'rb')}  # post jason
    response = requests.post(url=api_upload_url, files=data)  # post 请求上传文件
    json_res = response.json()  # 返回转为json
    media_id = json_res['media_id']  # 提取返回ID
    data = {"msgtype": "file", "file": {"media_id": media_id}}  # post json
    r = requests.post(url=api_send_url, json=data)  # post请求消息
    return r  # 返回请求状态码

def exec_local_cmd(cmd):
    """ 执行执行bash命令 """
    result = shlex.os.system(cmd)
    if result != 0:
        print("执行失败: %s" % cmd)
        sys.exit(1)


def ansible_inventory(file):
    loader = DataLoader()
    inventory = InventoryManager(loader=loader, sources=file)
    # 获取变量
    variable = VariableManager(loader=loader,inventory=inventory)
    vars = variable.get_vars()
    groups = inventory.list_groups()
    
    hosts=[]
    for tag in groups:
        if tag  == 'all':
            hosts = vars['groups'][tag]
    return hosts
    

def filter_list(content,filter):
    """ 过滤文本中的内容返回列表"""
    lst = re.findall(rf'{filter}', content)
    return lst

if __name__ == '__main__':
    path = '/etc/ansible/check'
    dirs = os.listdir( path )

    for f in dirs:
        fullpath = os.path.join(path,f)
        if os.path.isfile(fullpath) and os.path.splitext(f)[1]=='.ini':
            ansible_inventory(fullpath)
        
            cmd = f"ansible -i {fullpath} all  -m shell -a 'curl -s http://10.147.113.190:10000/check.sh|bash' "
            print(cmd)
            p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
            p.wait()
            ret = p.stdout.read().decode().strip()
            print(ret)
            filename = '/opt/files/host_check/{}_host_check.txt'.format(os.path.splitext(f)[0])

            with open(filename,'w') as f:
                f.write(ret)

            tar_cmd="cd /opt/files;tar zcvf host_check.tar.gz host_check"
            exec_local_cmd(tar_cmd)
    wx_upload('/opt/files/host_check.tar.gz')
